package edu.byu.intex2.data.dao;

import edu.byu.intex2.data.bo.*;
import edu.byu.intex2.data.Cache;
import edu.byu.intex2.data.ConnectionPool;
import edu.byu.intex2.data.DataException;
import java.sql.*;
import java.util.List;
import java.util.LinkedList;

  /**
 * Customer Data Access Object
 * @author Adam Chavez
 */
public class CustomerDAO
{

  /////////////////////////////////////////////
  ///   Singleton code

  private static CustomerDAO instance = null;

  /** Creates a new instance of CustomerDAO */
  private CustomerDAO()
  {

  }//constructor

  /** Retrieves the single instance of this class */
  public static synchronized CustomerDAO getInstance()
  {
    if (instance == null)
    {
      instance = new CustomerDAO();
    }
    return instance;
  }//getInstance

  ////////////////////////////////////////////
  ///   CREATE methods

  /**
   * Creates a new Customer in the database
   * set alreadyInDB to false
   * put Customer in cache
   */
  public Customer create(String id) throws DataException
  {
    Customer customer = new Customer(id);
    customer.setObjectAlreadyInDB(false);
    Cache.getInstance().put(customer.getId(), customer);
    return customer;
  }//create


  ////////////////////////////////////////////
  ///   READ methods

  /**
   * Reads an existing Customer from the database
   * 1) Checks cache
   * 2) Gets a connection
   * 3) Calls read with connection argument
   */
  public Customer read(String id) throws DataException
  {
    if (Cache.getInstance().containsKey(id))
    {
      return (Customer)Cache.getInstance().get(id);
    }
    Connection conn = ConnectionPool.getInstance().get();
    try
    {
      return read(id, conn);
    }
    catch (Exception e)
    {
      throw new DataException("An error occurred while reading the business object information.", e);
    }
    finally
    {
      ConnectionPool.getInstance().release(conn);
    }
  }

  /**
   * Internal method to read an existing Customer from the database
   * 1) Check cache for object
   * 2) Create a prepared statement to execute sql query
   * 3) Create a resultset from the preparedstatement
   * 4) Return the Customer
   */
  synchronized Customer read(String id, Connection conn) throws Exception
  {
    if (Cache.getInstance().containsKey(id))
    {
      return (Customer)Cache.getInstance().get(id);
    }
    PreparedStatement stmt = conn.prepareStatement("select * from CUSTOMER, PERSON where person.id = customer.id and person.id = ?");
    try
    {
      stmt.setString(1, id);
      ResultSet rs = stmt.executeQuery();
      if (rs.next())
      {
        return readRecord(rs, conn);
      }//if
      throw new DataException("Customer with id '" + id + "' not found.");
    }
    finally
    {
      stmt.close();
    }
  }//read


  /**
   * Internal method to create a Customer object from a record
   * 1) Check cache for object
   * 2) Instantiate new Customer
   * 3) Set alreadyInDb to false
   * 4) Set all variables from result set
   * 5) Set dirty to true
   * 6) Return Customer
   */
  synchronized Customer readRecord(ResultSet rs, Connection conn) throws Exception
  {
    if (Cache.getInstance().containsKey(rs.getString("id")))
    {
      return (Customer)Cache.getInstance().get(rs.getString("id"));
    }
    Customer customer = new Customer(rs.getString("id"));
    customer.setObjectAlreadyInDB(true);
    Cache.getInstance().put(customer.getId(), customer);
    System.out.println("Result set" + rs.getString("FIRST_NAME"));
    customer.setFirstName(rs.getString("FIRST_NAME"));
    customer.setLastName(rs.getString("LAST_NAME"));
    customer.setAddress(rs.getString("ADDRESS"));
    customer.setPhone(rs.getString("PHONE"));
    customer.setHighPrice(Double.parseDouble(rs.getString("HIGH_PRICE")));
    customer.setLowPrice(Double.parseDouble(rs.getString("LOW_PRICE")));

    customer.setDirty(false);
    return customer;
  }//readRecord

  /////////////////////////////////////////////
  ///   UPDATE methods

  /** Saves an existing customer in the database */
  public void save(Customer customer) throws DataException
  {
   Connection conn = ConnectionPool.getInstance().get();
    try
    {
      save(customer, conn);
      conn.commit();
    }
    catch (Exception e)
    {
      try
      {
        conn.rollback();
      }
      catch (SQLException e2)
      {
        throw new DataException("Could not roll back the database transaction!", e2);
      }
      throw new DataException("An error occurred while saving the business object information.", e);
    }
    finally
    {
      ConnectionPool.getInstance().release(conn);
    }

  }

  /** Internal method to update a customer in the database */
  void save(Customer customer, Connection conn) throws Exception
  {
    Cache.getInstance().put(customer.getId(), customer);
    if (customer.isObjectAlreadyInDB() && customer.isDirty()) 
    {
      update(customer, conn);
    }
    else if (customer.isDirty())
    {
      insert(customer, conn);
    }
    
    /*for (SaleLine si: sale.getLines()) 
    {
      SaleLineDAO.getInstance().save(si, conn);
    }*/
  }

  /** Saves an existing customer to the database */
  private void update(Customer customer, Connection conn) throws Exception
  {
    PreparedStatement stmt = conn.prepareStatement("UPDATE person SET first_name=?, last_name=?, address=?, phone=? WHERE id=?");
    try
    {
      stmt.setString(1, customer.getFirstName());
      stmt.setString(2, customer.getLastName());
      stmt.setString(3, customer.getAddress());
      stmt.setString(4, customer.getPhone());
      stmt.setString(5, customer.getId());
      stmt.execute();
      customer.setDirty(false);
    }
    finally
    {
      stmt.close();
    }

    stmt = conn.prepareStatement("UPDATE customer SET high_price=?, low_price=? WHERE id=?");
    try
    {
      stmt.setString(1, customer.getHighPrice() + "");
      stmt.setString(2, customer.getLowPrice()+ "");
      stmt.setString(3, customer.getId());
      stmt.execute();
      customer.setDirty(false);
    }
    finally
    {
      stmt.close();
    }
  }

  /** Inserts a new customer into the database */
  private void insert(Customer customer, Connection conn) throws Exception
  {
    PreparedStatement stmt = conn.prepareStatement("INSERT INTO person VALUES (?, ?, ?, ?, ?)");
    try
    {
      stmt.setString(1, customer.getId());
      stmt.setString(2, customer.getFirstName());
      stmt.setString(3, customer.getLastName());
      stmt.setString(4, customer.getAddress());
      stmt.setString(5, customer.getPhone());
      stmt.execute();
      customer.setObjectAlreadyInDB(true);
      customer.setDirty(false);
    }
    finally
    {
      stmt.close();
    }

    stmt = conn.prepareStatement("INSERT INTO customer VALUES (?, ?, ?)");
    try
    {
      stmt.setString(1, customer.getId());
      stmt.setString(2, customer.getHighPrice() + "");
      stmt.setString(3, customer.getLowPrice()+ "");
      stmt.execute();
      customer.setDirty(false);
    }
    finally
    {
      stmt.close();
    }
  }





  /////////////////////////////////////////////////
  ///   DELETE methods

  /** We do not support deleting of business objects in this application */
  public void delete(Customer customer) throws DataException
  {
    throw new RuntimeException("Nice try. The delete function is not supported in this application.");
  }



  ////////////////////////////////////////////////
  ///   SEARCH methods

  /** Retrieves all conceptualcars from the database */
  public List<Customer> getAll() throws DataException
  {
    Connection conn = ConnectionPool.getInstance().get();
    try
    {
      PreparedStatement stmt = conn.prepareStatement("select *  from CUSTOMER JOIN person ON customer.id = person.id ORDER BY PERSON.id");
      return search(stmt, conn);
    }
    catch (Exception e)
    {
      try
      {
        conn.rollback();
      }
      catch (SQLException e2)
      {
        throw new DataException("Could not roll back the database transaction!", e2);
      }
      throw new DataException("An error occurred while reading the business object information.", e);
    }
    finally
    {
      ConnectionPool.getInstance().release(conn);
    }  //establish a connection, use a prepared statement, plug it into the search method return a list of empoyees
  }

/** Internal method to search by certain fields */
  private List<Customer> search(PreparedStatement stmt, Connection conn) throws Exception
  {
    List<Customer> customerList = new LinkedList<Customer>();
    try
    {
      ResultSet rs = stmt.executeQuery();
      while (rs.next())
      {
        customerList.add(readRecord(rs, conn));
      }
    }
    finally
    {
      stmt.close();
    }
    return customerList;
  }

 /* public List<Customer> getByName(String fName, String lName) throws Data Exception
  {
	//establish connection and prepared statement run it through the search method, return a list of customers matching the name(maybe more than one)
  }

  public Customer getByCustomerNumber(String EmpID) throws Data Exception
  {
	//establish connection and prepared statement run it through the search method, return an Customer matching the EmpID
  }*/



}
